package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemUserService systemUserService;

    //获取图形验证码
    @Override
    public CaptchaVo getCaptcha() {

        //创建验证码对象
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        //设置验证码类型，TYPE_DEFAULT表示字母+数字
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        //获取验证码中的文本，然后转换为小写
        String code = specCaptcha.text().toLowerCase();
        //设置Redis中存储正确验证码的key
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        //获取验证码的图片信息
        String image = specCaptcha.toBase64();
        //将正确的验证码存入到Redis中 并设置为60s过期
        stringRedisTemplate.opsForValue().set(key, code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        return new CaptchaVo(image, key);
   /*思路:
        创建验证码对象，设置长宽和存储数据的数量
        设置验证码的类型，数字或字母
        获取生成的验证码对象中的文本，并将其转换为小写
        使用UUID生成随机的key
        然后连接Redis，并设置键值对和失效时间（一分钟）
        获取其中的图片字符串和key值准备传给CaptchaVo
        最后返回

        需要导入EasyCaptcha的依赖 和Redis的场景启动器，和Redis必要的地址和端口号配置
        <dependency>
                 <groupId>com.github.whvcse</groupId>
                <artifactId>easy-captcha</artifactId>
        </dependency>
         */
    }

    //验证用户登录
    @Override
    public String login(LoginVo loginVo) {
        //1、判断验证码是否为空
            //获取传入的验证码
        String captchaCode = loginVo.getCaptchaCode();
        if(!StringUtils.hasText(captchaCode)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //2、判断验证码是否过期
        String code = stringRedisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        if(!StringUtils.hasText(code)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //3、判断验证码是否正确
        if(!captchaCode.equals(code)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //4、判断用户是否存在
        String username = loginVo.getUsername();
        LambdaQueryWrapper<SystemUser>  systemUserLambdaQueryWrapper = new LambdaQueryWrapper<>();
        systemUserLambdaQueryWrapper.eq(SystemUser::getUsername,username);
        SystemUser systemUser = systemUserService.getOne(systemUserLambdaQueryWrapper);
        if(systemUser == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //5、判断用户是否被禁用
        if(systemUser.getStatus().equals(BaseStatus.DISABLE)){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //6、判断密码是否正确
        if(!systemUser.getPassword().equals(DigestUtils.md5Hex(loginVo.getPassword()))){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //表示登录成功，根据userId和username创建token
        return JwtUtil.createToken(systemUser.getId(),systemUser.getUsername());
    }
}
